<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
<!--      <el-form-item label="客户 ID" prop="customerId">-->
<!--        <el-select v-model="formData.customerId" placeholder="请选择客户 ID">-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="客户名称" prop="customerName">-->
<!--        <el-input v-model="formData.customerName" placeholder="请输入客户名称" />-->
<!--      </el-form-item>-->
      <el-form-item label="客户名称" prop="customerId">
        <el-select v-model="formData.customerId" placeholder="请选择客户" clearable @change="handleCustomerChange">
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
<!--      <el-form-item label="箱型 ID" prop="boxTypeId">-->
<!--        <el-select v-model="formData.boxTypeId" placeholder="请选择箱型 ID">-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="箱型名称" prop="boxTypeName">-->
<!--        <el-input v-model="formData.boxTypeName" placeholder="请输入箱型名称" />-->
<!--      </el-form-item>-->
      <el-form-item label="箱型" prop="boxTypeId">
        <el-select v-model="formData.boxTypeId" placeholder="请选择箱型" clearable @change="handleBoxTypeChange">
          <el-option
            v-for="item in boxTypeList"
            :key="item.id"
            :label="item.productTypeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="材质 ID" prop="materialId">-->
<!--        <el-select v-model="formData.materialId" placeholder="请选择材质 ID">-->
<!--          <el-option label="请选择字典生成" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="材质名称" prop="materialName">-->
<!--        <el-input v-model="formData.materialName" placeholder="请输入材质名称" />-->
<!--      </el-form-item>-->

      <el-form-item label="材质名称" prop="materialId">
        <el-select v-model="formData.materialId" placeholder="请选择材质" clearable @change="handleMaterialChange">
          <el-option
            v-for="item in materialList"
            :key="item.id"
            :label="item.materialName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="长度" prop="length">
        <el-input v-model="formData.length" placeholder="请输入长度" />
      </el-form-item>
      <el-form-item label="宽度" prop="width">
        <el-input v-model="formData.width" placeholder="请输入宽度" />
      </el-form-item>
      <el-form-item label="高度" prop="height">
        <el-input v-model="formData.height" placeholder="请输入高度" />
      </el-form-item>
      <el-form-item label="长度2" prop="length2">
        <el-input v-model="formData.length2" placeholder="请输入长度2" />
      </el-form-item>
      <el-form-item label="宽度2" prop="width2">
        <el-input v-model="formData.width2" placeholder="请输入宽度2" />
      </el-form-item>
      <el-form-item label="高度2" prop="height2">
        <el-input v-model="formData.height2" placeholder="请输入高度2" />
      </el-form-item>
      <el-form-item label="楞型" prop="fluteType">
        <el-input v-model="formData.fluteType" placeholder="请输入楞型" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { BaseBoxInnerOuterConfigApi, BaseBoxInnerOuterConfigVO } from '@/api/erp/baseboxinnerouterconfig'

/** ERP基础资料-箱型内外径设置 表单 */
defineOptions({ name: 'BaseBoxInnerOuterConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined,
  customerName: undefined,
  boxTypeId: undefined,
  boxTypeName: undefined,
  materialId: undefined,
  materialName: undefined,
  length: undefined,
  width: undefined,
  height: undefined,
  length2: undefined,
  width2: undefined,
  height2: undefined,
  fluteType: undefined
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户 ID不能为空', trigger: 'change' }],
  // customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  boxTypeId: [{ required: true, message: '箱型 ID不能为空', trigger: 'change' }],
  // boxTypeName: [{ required: true, message: '箱型名称不能为空', trigger: 'blur' }],
  materialId: [{ required: true, message: '材质 ID不能为空', trigger: 'change' }],
  // materialName: [{ required: true, message: '材质名称不能为空', trigger: 'blur' }],
  length: [{ required: true, message: '长度不能为空', trigger: 'blur' }],
  width: [{ required: true, message: '宽度不能为空', trigger: 'blur' }],
  height: [{ required: true, message: '高度不能为空', trigger: 'blur' }],
  length2: [{ required: true, message: '长度2不能为空', trigger: 'blur' }],
  width2: [{ required: true, message: '宽度2不能为空', trigger: 'blur' }],
  height2: [{ required: true, message: '高度2不能为空', trigger: 'blur' }],
  fluteType: [{ required: true, message: '楞型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseBoxInnerOuterConfigApi.getBaseBoxInnerOuterConfig(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BaseBoxInnerOuterConfigVO
    if (formType.value === 'create') {
      await BaseBoxInnerOuterConfigApi.createBaseBoxInnerOuterConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseBoxInnerOuterConfigApi.updateBaseBoxInnerOuterConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    customerName: undefined,
    boxTypeId: undefined,
    boxTypeName: undefined,
    materialId: undefined,
    materialName: undefined,
    length: undefined,
    width: undefined,
    height: undefined,
    length2: undefined,
    width2: undefined,
    height2: undefined,
    fluteType: undefined
  }
  formRef.value?.resetFields()
}

// ** 客户 & 材质列表 ** 
const customerList = ref<{ id: string; name: string }[]>([])
const materialList = ref<{ id: string; materialName: string }[]>([])
const boxTypeList = ref<{ id: string; productTypeName: string }[]>([])

/** 获取客户列表 */
const getAllBaseCustomer = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseCustomer();
    if (response) {
      customerList.value = response;
    }
  } catch (error) {
    console.error("获取客户列表失败:", error);
  }
};
/** 获取箱型 */
const getAllBoxType = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseBoxType();
    if (response) {
      boxTypeList.value = response;
    }
  } catch (error) {
    console.error("获取箱型列表失败:", error);
  }
};

/** 获取材质列表 */
const getAllBaseMaterial = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseMaterial();
    if (response) {
      materialList.value = response;
    }
  } catch (error) {
    console.error("获取材质列表失败:", error);
  }
};

/** 选择客户时，自动填充客户名称 */
const handleCustomerChange = (id: string) => {
  const selectedCustomer = customerList.value.find(item => item.id === id);
  formData.value.customerName = selectedCustomer ? selectedCustomer.name : "";
};

/** 选择客户时，自动填充客户名称 */
const handleBoxTypeChange = (id: string) => {
  const selectedBoxType = boxTypeList.value.find(item => item.id === id);
  formData.value.boxTypeName = selectedBoxType ? selectedBoxType.productTypeName : "";
};

/** 选择材质时，自动填充材质名称 */
const handleMaterialChange = (id: string) => {
  const selectedMaterial = materialList.value.find(item => item.id === id);
  formData.value.materialName = selectedMaterial ? selectedMaterial.materialName : "";
};

onMounted(() => {
  Promise.all([
    getAllBaseCustomer(), // 获取所有客户
    getAllBaseMaterial(),  // 获取所有材质
    getAllBoxType() // 获取所有箱型
  ])
})
</script>
